//index.js
//获取应用实例
var common = require('../../utils/common.js');
const app = getApp()
Page({
  data: {
    myinfo: [],
    friends: [],
    cards: [],
    items: [],
    itemordersw: true,
    itemfavsw: false,
    freeordersw: false,
    sku: '',
    isfav: false,
    refresh: false,
    isFromSearch: true,
    searchLoading: true,
    searchLoadingComplete: false,
    callbackcount: 10,
    orderPageNum: 1,
    favPageNum: 1,
    freePageNum: 1,
    avatar: '',
    isIphoneX: false,
    statusBarHeight: app.globalData.statusBarHeight,
    windowHeight: app.globalData.windowHeight,
    detailedtc: false,
    sharetc: false,
    sharepic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc2.png',
    shareData: [],
    news: app.globalData.newnotice,
    oldsharetc: false,
    oldsharepic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc3.png',
    sharesucctc: false,
    sharesucc: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharesuccess.png',
    sharesuccData: [],
    socketMessage: [],
    formId: '',
    socketMessagesw: false,
    sharepictc: false,
    shareimg: '',
    loading: false,
    logined: false,
    storeManager: false,
    invitationCode:'dasdsada',
    todayFans: 30,
    totalFans: 100,
    solitaires:[],
    sessionId: '',
    userId:'',
    itemstu: false,
    scrollHeight:'',
    scorllNav: false,
    weixin:'1231231',
    hasLoginTc: false,
    freeItems:[],
    tabnav: [
      {
        name: '我的接龙',
        path: '/app/v2/skusolitaire/my'
      },
      {
        name: '我的免单',
        path: ''
      },
      {
        name: '已购商品',
        path: ''
      }
    ],
    currentTab: 0,
    orderItems:[],
    jlpage: 1,
    loading1: true,
    loading2: true,
    loading3: true,
    freepage: 1,
    orderpage: 1,
    nojlItem: false,
    nofreeItem: false,
    noorderItem: false,
    tabtop: '',
    screenHeight: app.globalData.screenHeight,
    pixelRatio: app.globalData.pixelRatio,
    windowWidth: app.globalData.windowWidth,
    sharejlitem: [],
    shareFreeitem: [],
    shopitems:[],
    shopfreeitems:[],
    systemitems:[],
    shopInfo: [],
    shareStore: false,
    sharetxt: '',
    shopfreeloaded: false,
    shopitemloaded: false,
    systemitemsloaded: false
  },
  onShareAppMessage: function (res) {
    console.log(this.data.currentTab)
    console.log(this.data.shareStore)
    console.log(res)
    if (res.from === 'button') {
      var path = ''
      var imageUrl = ''
      var title = ''
      if(this.data.shareStore){
        if(app.globalData.userInfo.hasShop){
          title = app.globalData.userInfo.nickname + '的小铺砸锅卖铁打折了，快来看看吧'
          imageUrl = this.data.imgSrcSmall
          path = '/pages/shareShop/shareShop?userId=' + app.globalData.userInfo.userId
        }else{
          title = app.globalData.userInfo.nickname + '邀请您上京多多省更多'
          imageUrl = this.data.imgSrcSmall
          path = '/pages/shareShop/shareShop?userId=' + app.globalData.userInfo.userId
        }
          
      }else{
        console.log(1)
        if(this.data.currentTab == 0){
          console.log(1)
          title = app.globalData.userInfo.nickname + '邀请你参加接龙'
          imageUrl = this.data.imgSrcSmall
          path = '/pages/shareSolitaireD/shareSolitaireD?solitaireId=' + this.data.sharejlitem.solitaireId + '&userId=' + app.globalData.userInfo.userId
          console.log(path)
        }else if(this.data.currentTab == 1){
          let fromOf = ''
          if(app.globalData.userInfo.hasShop){
            fromOf = 'fsk'
          }else{
            fromOf = 'fod'
          }
          path = '/pages/activeitemdetail/activeitemdetail?userId=' + app.globalData.userInfo.userId + '&sku=' + this.data.shareFreeitem.skuId + '&f=t&fr=' + this.data.shareFreeitem.freeId + '&fO=' + fromOf
          imageUrl = this.data.imgSrcSmall
          title = '快帮帮我，就差你一个了'
        }else if(this.data.currentTab == 2){
          if(app.globalData.userInfo.hasShop){
            fromOf = 'fsk'
          }else{
            fromOf = 'fod'
          }
          title = app.globalData.userInfo.nickname + '分享给你一个超值特价商品，快来看看吧'
          path = '/pages/itemdetail/itemdetail?userId=' + app.globalData.userInfo.userId + '&sku=' + this.data.shareFreeitem.skuId + '&fO=' + fromOf
          imageUrl = this.data.imgSrcSmall
          
        }
      }
      
      console.log(path)
    }
    return {
      title: title,
      path: path,
      imageUrl: imageUrl
    }
  },
  onLoad: function () {
    if (app.globalData.userInfo !== null && app.globalData.userInfo.hasShop) {
      wx.setTabBarItem({
        index: 2,
        text: '我的小店',
        success(res) {
          console.log(res)
        },
        fail(res) {
          console.log(res)
        }
      })
    } else {
      wx.setTabBarItem({
        index: 2,
        text: '我要开店',
        success(res) {
          console.log(res)
        },
        fail(res) {
          console.log(res)
        }
      })
    }
    console.log(app.globalData.sessionId !== undefined)
    if (app.globalData.sessionId !== undefined){
      console.log('true',app.globalData.sessionId)
      this.setData({
        logined: true,
        sessionId: app.globalData.sessionId,
        userId: app.globalData.userId
      })
      this.getuserinfoData()
      this.invitatoryData()
      this.getfreeorderData()
      this.getShopData()
      this.getSolitaireData()
    }else{
      console.log('false', app.globalData.sessionId)
      this.setData({
        logined: false,
        hasLoginTc: true
      })
      var row = 104
      // this.loginTip(row)
    }
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      isIphoneX: isIphoneX
    })
    if (app.globalData.fromShopkeeper){
      // wx.hideTabBar()
    }
    
  },
  onShow(){
    var that = this;
    this.loginModal = this.selectComponent("#loginModal");
    let query = wx.createSelectorQuery()
    if(app.globalData.utop == ''){
      setTimeout(() => {
        query.select('.tabnav').boundingClientRect( (rect) => {
          console.log(rect)
          if(rect !== null){
            var scrollHeight = rect.top - rect.height - that.data.statusBarHeight - 88
            that.setData({
              tabtop: scrollHeight
            })
            app.globalData.utop = scrollHeight
          }
        }).exec()
      }, 1000);
    }else{
      this.setData({
        tabtop: app.globalData.utop
      })
    }
    
    if (app.globalData.sessionId !== undefined) {
      console.log('true', app.globalData.sessionId)
      this.setData({
        logined: true,
        sessionId: app.globalData.sessionId,
        userId: app.globalData.userId
      })
      this.getuserinfoData()
      this.invitatoryData()
      this.getfreeorderData()
      this.getShopData()
      this.getSolitaireData()
    } else {
      console.log('false', app.globalData.sessionId)
      this.setData({
        logined: false,
        hasLoginTc: true
      })
      var row = 104
      // this.loginTip(row)
    }
  },
  async runLogin(){
    let res = await app.login(app.globalData.thisshareTicket)
    this.setData({
      logined: true,
    })
    this.waitLogin()
    console.log(this.data.logined)

  },
  waitLogin() {
    const that = this
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (app.globalData.sessionId && app.globalData.userId) {
          clearInterval(timer);
          resolve(app.globalData);
          that.setData({
            logined: true,
            userInfo: app.globalData.userInfo,
            hasLoginTc: true
          })
          console.log(that.data.logined)
          wx.hideLoading()
          that.getuserinfoData()
          that.invitatoryData()
          that.getfreeorderData()
          that.getShopData()
          that.getTabBar()
          that.setData({
            hasShop: true,
          })
        } else {
          //todo 信息构建中
          that.setData({
            hasLoginTc: false
          })
        }
      }, 250);
    });

  },
  loginTip(row){
    console.log(row)
    const that = this
    console.log(this.data.hasLoginTc)
    // if (this.data.hasLoginTc){
    //   that.setData({
    //     hasLoginTc: false
    //   })
    //   wx.showModal({
    //     title: '提示',
    //     content: '你需要登录，才能享受优惠',
    //     success(res) {
    //       if (res.confirm) {
    //         console.log('用户点击确定')
    //         wx.showLoading({
    //           title: '登录中...',
    //         })
    //         that.runLogin()
    //       } else if (res.cancel) {
    //         console.log('用户点击取消')
    //       }
    //     }
    //   })
    // }
    this.loginModal.showPopup();
    
  },
  postformid(skuId) {
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        skuId: skuId,
        formId: that.data.formId
      },
      url: app.globalData.url + "/app/v2/goods/getShareLink",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  buybtn1(e) {
    console.log(e)
    app.globalData.item = e.currentTarget.dataset.item
    console.log(app.globalData.item)
    wx.navigateTo({
      url: '/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.item.skuId,
      success(res){

      },
      fail(res){
        console.log(res)
      }
    })
  },
  buybtn2(e) {
    console.log(e)
    console.log(app.globalData.item)
    if(app.globalData.userInfo.hasShop){
      fromOf = 'fsk'
    }else{
      fromOf = 'fod'
    }
    console.log('/pages/freeItemdetail/freeItemdetail?sku=' + e.currentTarget.dataset.item.sku.skuId + '&fr=' + e.currentTarget.dataset.item.freeId + '&f=t' + '&mycenter=true' + '&userId=' + app.globalData.userId + '&fO=' + fromOf)
    wx.navigateTo({
      url: '/pages/freeItemdetail/freeItemdetail?sku=' + e.currentTarget.dataset.item.sku.skuId + '&fr=' + e.currentTarget.dataset.item.freeId + '&f=t' + '&mycenter=true' + '&userId=' + app.globalData.userId
    })
  },
  closesptc() {
    this.setData({
      sharepictc: false,
      shareimg: ''
    });
  },
  saveimg() {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareimg,
      success(res) {
        wx.hideToast()
        app.globalData.newnotice = true
        that.setData({
          news: app.globalData.newnotice
        });
        console.log(that.data.news)
        wx.showModal({
          title: '提示',
          content: '分享图已经存到您的相册',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                sharepictc: false,
                shareimg: ''
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  },
  close() {
    this.setData({
      cbsw: false
    });
  },
  closetc() {
    this.setData({
      firstuser: false
    });
  },
  closedtc() {
    this.setData({
      detailedtc: false
    });
  },
  activelink() {
    this.setData({
      firstuser: false,
      currentTab: 2,
      sharesucctc: false
    })
  },
  tiptc() {
    this.setData({
      detailedtc: true
    })
  },
  shareSubmit(e) {
    console.log(e)
    this.setData({
      sharetc: true,
      shareData: e.currentTarget.dataset.item,
      formId: e.detail.formId
    });
    console.log(this.data.shareData)
  },

  closestc() {
    this.setData({
      sharetc: false,
      shareData: []
    });
  },
  closesutc() {
    this.setData({
      sharesucctc: false,
      shareData: []
    });
  },
  getuserinfoData: function() {
    const that = this
    common.post({
      url: '/app/user/getInfo', data: { sessionId: this.data.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          that.setData({
            myinfo: res.data.data,
            avatar: res.data.data.avatar
          });
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  invitatoryData: function () {
     const that = this
    common.post({
      url: '/app/user/listInvitatory', data: { sessionId: this.data.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          that.setData({
            friends: res.data.data,
          });
        } else if (res.data.code == -9998){
          if (app.globalData.sessionId !== undefined){
            that.setData({
              hasLoginTc: true
            })
          }
          
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  myecarddata: function () {
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        pageNo: '1',
        sessionId: app.globalData.sessionId
      },
      url: app.globalData.url + "/app/user/listJDecard",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        that.setData({
          cards: data.data.data,
        });
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  getfreeorderData: function () {
    const that = this
    common.post({
      url: '/app/user/listEnableFreeShopping', data: { sessionId: this.data.sessionId, pageNo: 1 }
    })
    .then((res) => {
      console.log(res.data)
      if (res.data.code == 0) {
        that.setData({
          freeItems: res.data.data,
        });
        if(res.data.total == 0){
          that.setData({
            nofreeItem: true,
            loading2: false
          })
        }else if(res.data.total < 11){
          that.setData({
            loading2: false
          })
          
        }
      }
    }).catch((res) => {
      console.log(res)
      app.timeOutTip()
    })
  },
  getfreeorderDatapage(){
    const that = this;
    var page = that.data.freepage + 1;
    common.post({ url: '/app/v2/skusolitaire/my', data: { sessionId: app.globalData.sessionId, pageNo: page } })
      .then((res) => {
        var data = that.data.freeItems;
        console.log(res.data)
        if (that.data.freepage * 10 < res.data.total) {
          that.setData({
            freepage: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
          }
          setTimeout(() => {
            console.log(data)
            that.setData({
              freeItems: data,
            })
          }, 300);
        } else {
          console.log('没有了')
          that.setData({
            loading2: false
          })
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  getorderitemData: function () {
    const that = this
    common.post({
      url: '/app/user/listOrder', data: { sessionId: this.data.sessionId, pageNo: 1 }
    })
    .then((res) => {
      console.log(res.data)
      if (res.data.code == 0) {
        that.setData({
          orderItems: res.data.data,
        });
        if(res.data.total == 0){
          that.setData({
            noorderItem: true,
            loading3: false
          })
        }else if(res.data.total < 11){
          that.setData({
            loading3: false
          })
        }
      }
    }).catch((res) => {
      console.log(res)
      app.timeOutTip()
    })
  },
  getorderitemDatapage(){
    const that = this;
    var page = that.data.orderpage + 1;
    common.post({ url: '/app/v2/skusolitaire/my', data: { sessionId: app.globalData.sessionId, pageNo: page } })
      .then((res) => {
        var data = that.data.orderItems;
        console.log(res.data)
        if (that.data.orderpage * 10 < res.data.total) {
          that.setData({
            orderpage: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
          }
          setTimeout(() => {
            console.log(data)
            that.setData({
              orderItems: data,
            })
          }, 300);
        } else {
          console.log('没有了')
          that.setData({
            loading3: false
          })
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  getfavitemData: function () {
    var that = this
    if (app.globalData.sessionId) {
      this.setData({
        isfav: true,
        itemordersw: false,
        itemfavsw: true,
        freeordersw: false,
        refresh2: true,
        items: [],
        loading: true
      });
      const requestTask = wx.request({
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          pageNo: '1',
          sessionId: app.globalData.sessionId
        },
        url: app.globalData.url + "/app/user/listCollect",
        async: true,
        timeout: 10000,
        success: function (data) {
          console.log(data)
          that.setData({
            items: data.data.data,
            refresh2: false,
            loading: false
          });
        },
        error: function (textStatus) {
          console.error(textStatus);
        },
        complete: function (XMLHttpRequest, status) {
          if (status == 'timeout') {
            requestTask.abort()    // 超时后中断请求
            wx.showModal({
              title: '提示',
              content: '网络超时，请重试',
              showCancel: 'false',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              }
            })
          }
        }
      })
    } else {
      var row = 899
      this.loginTip(row)
    }
    
    
  },
  copycardnumber: function(e){
    console.log(e)
    wx.setClipboardData({
      data: e.currentTarget.dataset.code,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) // data
            wx.showToast({
              title: '复制成功',
              icon: 'success',
              duration: 2000
            });
          }
        })
      }
    })
  },
  onReachBottom: function (e) {
    console.log('bottom')
    console.log(this.data.currentTab)
    switch(this.data.currentTab){
      case 0:
        this.getSolitaireDatapage()
        break
      case 1:
        this.getfreeorderDatapage()
        break
      case 2:
        this.getorderitemDatapage()
        break
    }
  },
  onPageScroll: function (e) {
    // console.log(e.scrollTop,this.data.tabtop)
    if(e.scrollTop >= this.data.tabtop){
      if(!this.data.scorllNav){
        this.setData({
          scorllNav: true
        })
      }
    }else{
      if(this.data.scorllNav){
        this.setData({
          scorllNav: false
        })
      }
    }
  },
  myecardlink: function(){
    wx.redirectTo({
      url: '/pages/mycard/mycard'
    })
  },
  back: function () {
    if (app.globalData.center){
      wx.redirectTo({
        url: '/pages/itemlist/itemlist'
      })
    }else{
      wx.navigateBack()
    }
    
  },
  exchangelink: function () {
    if (app.globalData.sessionId) {
      wx.navigateTo({
        url: '/pages/exchange/exchange'
      })
    } else {
      var row = 1171
      this.loginTip(row)
    }
    
  },
  messagelink: function () {
    wx.navigateTo({
      url: '/pages/notice/notice'
    })
  },
  toSubordinate(){
    wx.navigateTo({
      url: '/pages/subordinate/subordinate',
      success: function (res) {
        console.log('toSubordinate')
      },
      fail:function(res){
        console.log(res)
      }
    })
  },
  toProfits(){
    wx.navigateTo({
      url: '/pages/profits/profits',
      success: function (res) {
        console.log('toProfits')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toSolitaire(){
    wx.navigateTo({
      url: '/pages/solitaire/solitaire',
      success: function (res) {
        console.log('toSolitaire')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  getSolitaireData(){
    const that = this
    common.post({
      url: '/app/v2/skusolitaire/my', data: { sessionId: app.globalData.sessionId, pageNo:1 }
    })
    .then((res) => {
      console.log(res.data)
      if (res.data.code == 0) {
        that.setData({
          solitaires: res.data.data,
        })
        if(res.data.total == 0){
          that.setData({
            nojlItem: true,
            loading1: false
          })
        }else if(res.data.total < 11){
          that.setData({
            loading1: false
          })
        }
      } else if (res.data.code == "-9998") {
        app.globalData.sessionId = undefined
        var row = 1228
        that.loginTip(row)
      } else {
        console.log(res)
      }
    }).catch((res) => {
      console.log(res)
    })
  },
  getSolitaireDatapage(){
    const that = this;
    var page = that.data.jlpage + 1;
    common.post({ url: '/app/v2/skusolitaire/my', data: { sessionId: app.globalData.sessionId, pageNo: page } })
      .then((res) => {
        var data = that.data.solitaires;
        console.log(res.data)
        if (that.data.jlpage * 10 < res.data.total) {
          that.setData({
            jlpage: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
          }
          setTimeout(() => {
            console.log(data)
            that.setData({
              solitaires: data,
            })
          }, 300);
        } else {
          console.log('没有了')
          that.setData({
            loading1: false
          })
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  toSolitaireDetailed(e){
    console.log(e.currentTarget.dataset.solitaireid)
    wx.navigateTo({
      url: '/pages/solitaireDetailed/solitaireDetailed?solitaireId=' + e.currentTarget.dataset.solitaireid,
      success: function (res) {
        console.log('toSolitaire')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  getShopData() {
    const that = this
    common.post({
      url: '/app/v2/shop/shopInfo', data: { sessionId: this.data.sessionId, userId: this.data.userId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          that.setData({
            shopInfo: res.data.data
          })
          console.log(res.data.data.status)
          if (res.data.data.status == 2) {
            that.setData({
              storeManager: true
            })
            that.getSolitaireData()
          }
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  wxhelp() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '您的专属辅导微信号:\r\n' + this.data.weixin + '\r\n关于省钱赚钱的问题,请复制微信号去微信添加好友咨询\r\n添加时请备注:京多多会员',
      confirmText: '复制',
      confirmColor: '#2365b7',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          console.log(that.data.weixin)
          wx.setClipboardData({
            data: that.data.weixin,
            success(res) {
              wx.getClipboardData({
                success(res) {
                  console.log(res.data) // data
                }
              })
            },
            fail(res){
              console.log(res)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  toSharePoster(){
    wx.navigateTo({
      url: '/pages/sharePoster/sharePoster',
      success: function (res) {
        console.log('toSharePoster')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  copyInviteCode(){
    wx.setClipboardData({
      data: this.data.myinfo.inviteCode,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log(res.data) // data
          }
        })
      },
      fail(res) {
        console.log(res)
      }
    })
  },
  toInitiateJl(){
    wx.navigateTo({
      url: '/pages/initiateJl/initiateJl',
      success: function (res) {
        console.log('toInitiateJl')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  swichNav(e){
    console.log(e.currentTarget.dataset.current)
    var current = e.currentTarget.dataset.current
    this.setData({
      currentTab: current,
    })
    switch(current){
      case 0:
        if(this.data.solitaires.length < 1){
          this.getSolitaireData()
        }
        break
      case 1:
        if(this.data.freeItems.length < 1){
          this.getfreeorderData()
        }
        
        break
      case 2:
        if(this.data.orderItems.length < 1){
          this.getorderitemData()
        }
        break
    }
  },
  toSolitaire(){
    wx.navigateTo({
      url: '/pages/initiateJl/initiateJl',
      success: function (res) {
        console.log('toInitiateJl')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toMyStone(){
    wx.switchTab({
      url: '/pages/myStore/myStore',
      success: function (res) {
        console.log('toMyStore')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  // 接龙分享begin
  shareJl(e){
    console.log(e)
    this.setData({
      sharejlitem: e.currentTarget.dataset.item
    })
    console.log(this.data.sharejlitem)
    this.canvas()
  },
  // 选择画布
  canvas(){
    wx.showLoading({
      title: '分享图生成中',
      mask: true
    })
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 828;//本地图像的width
      canvas.height = 1472;//本地图像的height
      this.render(canvas, ctx);
    }).exec()
  },
  canvas1(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render2(canvas, ctx);
    }).exec()
  },
 
  // 生成分享图

  render(canvas, ctx) {
    const that = this
    this.drawIteminfo(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemPic(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawItemTag(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawAvatar(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawDcode(ctx,canvas).then(function(){
              console.log('第五步完成')
              that.drawjlinfo(ctx,canvas).then(function(){
                console.log('第六步完成')
                that.drawCanvas(canvas)
                that.canvas1()
              })
            })
          })
        })
      })
    })
  },
  render2(canvas, ctx){
    const that = this
    that.drawSmallpic(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawSmalltag(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawCanvas2(canvas)
      })
    })
  },
  // 绘制分享小图
  drawSmallpic(ctx,canvas){
    const that = this
    let item = this.data.sharejlitem.sku,
        txt1 = '这个超值商品好多人都在抢购呢！',
        txt2 = '已经' + this.data.sharejlitem.partnerCount + '人参与了接龙>'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 500, 500);
        ctx.fillStyle = '#FF5555'
        ctx.fillRect(0,320,500,80)
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 16, 351);
        ctx.fillStyle = "#FFF617";
        ctx.fillText(txt2, 16, 385);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  // 绘制商品标签
  drawSmalltag(ctx,canvas){
    const that = this
    let item = this.data.sharejlitem.sku
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 12, 12, 200, 36);
        ctx.font = "20px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 146, 38);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 46, 38);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制内容
  drawIteminfo(ctx,canvas){
    console.log('开始绘图')
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }

        finalStr += name[i];
        if (length > 18) {
          break;
        }
      }
      return finalStr;
    }
    var row2size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        if (length > 19) {
          finalStr += name[i];
        }
        if (length > 35) {
          break;
        }
      }
      return finalStr + '...';
    }
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    console.log(this.data.sharejlitem)
    let item = this.data.sharejlitem.sku,
        solitaire = this.data.sharejlitem,
        itemName = item.title,
        str1 = row1size(itemName),
        str2 = row2size(itemName),
        priceNew = '',
        priceOld = format(item.price),
        priceNewTxt = '抢券价',
        priceOldTxt = '京东价'
        // txt1 = solitaire.partnerCount + '人参与了群接龙567'
    if(item.coupons){
      priceNew = format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = priceOld
    }
    const that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        ctx.font = "30px PingFangSC-Medium";
        ctx.fillStyle = "#363636";
        ctx.textAlign = 'center';
        ctx.fillText(str1, 414, 904);
        ctx.fillText(str2, 414, 946);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.fillText(priceNewTxt, 303, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceNew, 303, 1058);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#505050";
        ctx.fillText(priceOldTxt, 530, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceOld, 530, 1058);
        let lineWidth = ctx.measureText(priceOld).width
        console.log('线长度',lineWidth)
        ctx.beginPath()
        ctx.strokeStyle = '#D6D6D6'
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1008)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1044)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.strokeStyle = '#505050'
        ctx.lineWidth = 2;
        let lineX1 = 530 - lineWidth/2,
            lineX2 = 530 + lineWidth/2
        ctx.moveTo(lineX1, 1040)
        ctx.lineTo(lineX2, 1040)
        ctx.stroke()
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/zc_share@3x.jpg'
    })
  },
  drawjlinfo(ctx,canvas){
    let txt = this.data.sharejlitem.partnerCount + '人参与了群接龙'
    let x = 120,y = 1120, r = 36, w = 600, h = 72
    const that = this;
    return new Promise(function (resolve, reject) {
      ctx.save()
      ctx.beginPath()
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      // 这里是使用 fill 还是 stroke都可以，二选一即可
      ctx.setFillStyle = 'transparent'
      // ctx.setStrokeStyle('transparent')
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
      // 右上角
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
      // 左下角
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
      ctx.strokeStyle = '#FF5555'
      ctx.lineWidth = '2'
      ctx.stroke()
      ctx.closePath()
      // 剪切
      ctx.clip()
      ctx.restore();
      ctx.textAlign = 'center';
      ctx.fillStyle = "#FF5555";
      ctx.font = "32px PingFangSC-Medium";
      ctx.fillText(txt, 414, 1165);
      resolve()
    })
  },
  // 绘制商品图
  drawItemPic(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        var x = 134,y = 264, r = 8, w = 560, h = 560
        ctx.save()
        ctx.beginPath()
        // ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        // ctx.stroke()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.drawImage(img, 134, 264, 560, 560);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.sharejlitem.sku.image
    })
  },
  // 绘制标签
  drawItemTag(ctx,canvas){
    const that = this
    let item = this.data.sharejlitem.sku
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 292, 798, 244, 52);
        ctx.font = "26px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 454, 834);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 330, 834);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制头像
  drawAvatar(ctx,canvas){
    const that = this
    let txt1 = this.data.sharejlitem.organizer.nickName + ' 邀请你参与接龙',
        txt2 = '长按识别二维码进入京多多'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.sharejlitem.organizer.avatar
    })
  },
  // 绘制二维码
  drawDcode(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + app.globalData.userInfo.userId + '&solitaireId=' + that.data.sharejlitem.solitaireId
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/shareSolitaireD/shareSolitaireD',
          page: 'pages/itemlist/itemlist',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 生成图片
  drawCanvas(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          wx.hideLoading()
        }
      })
    })
  },
  drawCanvas2(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true,
            sharetxt: '邀请群成员参与接龙吧'
          })
          wx.hideLoading()
        }
      })
    })
  },
  // 接龙分享end
  
  // 免单分享begin
  shareFree(e){
    console.log(e)
    this.setData({
      shareFreeitem: e.currentTarget.dataset.item
    })
    console.log(this.data.shareFreeitem)
    this.canvas3()
  },
  // 选择画布
  canvas3(){
    wx.showLoading({
      title: '分享图生成中',
      mask: true
    })
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 828;//本地图像的width
      canvas.height = 1472;//本地图像的height
      this.render3(canvas, ctx);
    }).exec()
  },
  canvas4(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render4(canvas, ctx);
    }).exec()
  },
 
  // 生成分享图

  render3(canvas, ctx) {
    const that = this
    this.drawIteminfo2(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemPic2(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawItemTag2(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawAvatar2(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawDcode2(ctx,canvas).then(function(){
              console.log('第五步完成')
              if(that.data.shareFreeitem.users.length == 0){
                that.drawFriends(ctx,canvas).then(function(){
                  console.log('第六步完成，已生成分享大图')
                  that.drawCanvas3(canvas)
                  console.log('开始生成分享小图')
                  that.canvas4()
                })
              }else if(that.data.shareFreeitem.users.length == 1){
                that.drawFriends1(ctx,canvas).then(function(){
                  console.log('第六步完成')
                  that.drawFriendsBig1(ctx,canvas).then(function(){
                    console.log('第七步完成，已生成分享大图')
                    that.drawCanvas3(canvas)
                    console.log('开始生成分享小图')
                    that.canvas4()
                  })
                })
              }else if(that.data.shareFreeitem.users.length >= 2){
                that.drawFriends2(ctx,canvas).then(function(){
                  console.log('第六步完成')
                  that.drawFriendsBig1(ctx,canvas).then(function(){
                    console.log('第七步完成')
                    that.drawFriendsBig2(ctx,canvas).then(function(){
                      console.log('第八步完成，已生成分享大图')
                      that.drawCanvas3(canvas)
                      console.log('开始生成分享小图')
                      that.canvas4()
                    })
                  })
                })
              }
            })
          })
        })
      })
    })
  },
  render4(canvas, ctx){
    const that = this
    that.drawSmallpic2(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawSmalltag2(ctx,canvas).then(function(){
        console.log('第二步完成')
        if(that.data.shareFreeitem.users.length == 0){
          that.drawSmallFriend(ctx,canvas).then(function(){
            console.log('完成绘制')
            that.drawCanvas4(canvas)
          })
        }else if(that.data.shareFreeitem.users.length == 1){
          that.drawSmallFriend1(ctx,canvas).then(function(){
            console.log('第三步完成')
            that.drawOneFriend1(ctx,canvas).then(function(){
              console.log('完成绘制')
              that.drawCanvas4(canvas)
            })
            
          })
        }else if(that.data.shareFreeitem.users.length >= 2){
          that.drawSmallFriend2(ctx,canvas).then(function(){
            console.log('第三步完成')
            that.drawOneFriend1(ctx,canvas).then(function(){
              console.log('第四步完成')
              that.drawOneFriend2(ctx,canvas).then(function(){
                console.log('完成绘制')
                that.drawCanvas4(canvas)
              })
            })
          })
        }
      })
    })
  },
  // 绘制分享小图
  drawSmallpic2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 500, 500);
        ctx.fillStyle = '#FFE232'
        ctx.fillRect(0,320,500,80)
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillStyle = "#000";
        ctx.textAlign = 'left';
        ctx.fillText('3人帮TA助力就免费得', 16, 368);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shareFreeitem.sku.image
    })
  },
  // 绘制商品标签
  drawSmalltag2(ctx,canvas){
    const that = this
    var goodCommentsRate = '100'
    if(this.data.shareFreeitem.sku.goodCommentsRate > 0){
      goodCommentsRate = this.data.shareFreeitem.sku.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 12, 12, 200, 36);
        ctx.font = "20px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 146, 38);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 46, 38);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制小图头像
  drawSmallFriend(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 276, 328, 64, 64);
        ctx.drawImage(img, 348, 328, 64, 64);
        ctx.drawImage(img, 420, 328, 64, 64);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#000";
        ctx.textAlign = 'center';
        ctx.fillText('1', 308, 368);
        ctx.fillText('2', 380, 368);
        ctx.fillText('3', 452, 368);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/pel_share_b@3x.png'
    })
  },
  // 小图一个好友时候
  drawSmallFriend1(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.friends.length == 1){
          ctx.drawImage(img, 348, 328, 64, 64);
          ctx.drawImage(img, 420, 328, 64, 64);
          ctx.font = "bold 26px PingFangSC-Semibold";
          ctx.fillStyle = "#fff";
          ctx.textAlign = 'center';
          ctx.fillText('2', 380, 368);
          ctx.fillText('3', 452, 368);
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/pel_share_b@3x.png'
    })
  },
  // 小图两个好友时候
  drawSmallFriend2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.friends.length >= 2){
          ctx.drawImage(img, 420, 328, 64, 64);
          ctx.font = "bold 26px PingFangSC-Semibold";
          ctx.fillStyle = "#fff";
          ctx.textAlign = 'center';
          ctx.fillText('3', 452, 368);
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/pel_share_b@3x.png'
    })
  },
  // 绘制小图一个好友头像
  drawOneFriend1(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.shareFreeitem.users.length >= 1){
          ctx.beginPath()
          let r = 32, x = 276, y = 328
          ctx.save()
          ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
          ctx.clip()
          ctx.drawImage(img, 276, 328, 64, 64);
          ctx.restore()
          ctx.strokeStyle = "white";
          ctx.lineWidth = '2'
          ctx.stroke();
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shareFreeitem.users[0].avatar
    })
  },
  // 绘制小图两个好友头像
  drawOneFriend2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.shareFreeitem.user.length >= 1){
          ctx.beginPath()
          let r = 32, x = 348, y = 328
          ctx.save()
          ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
          ctx.clip()
          ctx.drawImage(img, 348, 328, 64, 64);
          ctx.restore()
          ctx.strokeStyle = "white";
          ctx.lineWidth = '2'
          ctx.stroke();
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shareFreeitem.users[1].avatar
    })
  },
  // 绘制好友
  drawFriends(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = '待助力'
      img2.onload = (e) => {
        console.log('img2 loaded')
        ctx.drawImage(img2, 190, 1060, 96, 96);
        ctx.drawImage(img2, 366, 1060, 96, 96);
        ctx.drawImage(img2, 542, 1060, 96, 96);
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 239, 1184);
        ctx.fillText(str, 415, 1184);
        ctx.fillText(str, 595, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = '/img/new/people_redbg@3x.png'
    })
  },
  // 大图一个好友时候
  drawFriends1(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = '待助力'
      img2.onload = (e) => {
        console.log('img2 loaded')
        ctx.drawImage(img2, 366, 1060, 96, 96);
        ctx.drawImage(img2, 542, 1060, 96, 96);
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 415, 1184);
        ctx.fillText(str, 595, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = '/img/new/people_redbg@3x.png'
    })
  },
  // 大图两个好友时候
  drawFriends2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = '待助力'
      img2.onload = (e) => {
        console.log('img2 loaded')
        ctx.drawImage(img2, 542, 1060, 96, 96);
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 595, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = '/img/new/people_redbg@3x.png'
    })
  },
  // 一个大图好友头像
  drawFriendsBig1(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = that.data.shareFreeitem.users[0].nickname
      img2.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 48, x = 190, y = 1060
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img2, 190, 1060, 96, 96);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 239, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = that.data.shareFreeitem.users[0].avatar
    })
  },
  // 两个大图好友头像
  drawFriendsBig2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = that.data.shareFreeitem.users[1].nickname
      img2.onload = (e) => {
        ctx.beginPath()
        let r = 48, x = 366, y = 1060
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img2, 366, 1060, 96, 96);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 415, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = that.data.shareFreeitem.users[1].avatar
    })
  },
  // 绘制内容
  drawIteminfo2(ctx,canvas){
    console.log('开始绘图')
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }

        finalStr += name[i];
        if (length > 18) {
          break;
        }
      }
      return finalStr;
    }
    var row2size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        if (length > 19) {
          finalStr += name[i];
        }
        if (length > 35) {
          break;
        }
      }
      return finalStr + '...';
    }
    console.log(this.data.shareFreeitem)
    var itemName = this.data.shareFreeitem.sku.title
    var str1 = row1size(itemName)
    var str2 = row2size(itemName)
    let that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        ctx.font = "30px PingFangSC-Medium";
        ctx.fillStyle = "#363636";
        ctx.textAlign = 'center';
        ctx.fillText(str1, 414, 904);
        ctx.fillText(str2, 414, 946);
        ctx.font = "32px PingFangSC-Regular";
        ctx.fillStyle = "#FF5555";
        ctx.fillText('3人助力TA就免费得', 414, 1022);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/zc_share@3x.jpg'
    })
  },
  // 绘制商品图
  drawItemPic2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        var x = 134,y = 264, r = 8, w = 560, h = 560
        ctx.save()
        // ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        // ctx.stroke()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.drawImage(img, 134, 264, 560, 560);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shareFreeitem.sku.image
    })
  },
  // 绘制标签
  drawItemTag2(ctx,canvas){
    const that = this
    var goodCommentsRate = '100'
    if(this.data.shareFreeitem.sku.goodCommentsRate > 0){
      goodCommentsRate = this.data.shareFreeitem.sku.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 292, 798, 244, 52);
        ctx.font = "26px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 454, 834);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 330, 834);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制头像
  drawAvatar2(ctx,canvas){
    const that = this
    let txt1 = app.globalData.userInfo.nickname + ' 邀请你0元得好物',
        txt2 = '长按识别二维码进入京多多'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = app.globalData.userInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode2(ctx,canvas){
    if(app.globalData.userInfo.hasShop){
      fromOf = '&fO=fsk'
    }else{
      fromOf = '&fO=fod'
    }
    const that = this
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + app.globalData.userInfo.userId + '&sku=' + that.data.shareFreeitem.sku.skuId + '&fr=' + that.data.shareFreeitem.freeId
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          page: 'pages/activeitemdetail/activeitemdetail',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 生成图片
  drawCanvas3(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          wx.hideLoading()
        }
      })
    })
  },
  drawCanvas4(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true,
            sharetxt: '3位好友助力后就可以免单哦'
          })
          wx.hideLoading()
        }
      })
    })
  },
  // 免单分享end

  // 已购商品分享begin
  buyedshare(e){
    this.setData({
      buyedItem: e.currentTarget.dataset.item
    })
    this.canvas5()
  },
  // 选择画布
  canvas5(){
    wx.showLoading({
      title: '分享图生成中',
      mask: true
    })
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 828;//本地图像的width
      canvas.height = 1472;//本地图像的height
      this.render5(canvas, ctx);
    }).exec()
  },
  canvas6(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render6(canvas, ctx);
    }).exec()
  },
 
  // 生成分享图

  render5(canvas, ctx) {
    const that = this
    this.drawIteminfo3(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemPic3(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawItemTag3(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawAvatar3(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawDcode3(ctx,canvas).then(function(){
              console.log('第五步完成')
              that.drawCashbackinfo3(ctx,canvas).then(function(){
                console.log('第六步完成')
                that.drawCanvas5(canvas)
                that.canvas6()
              })
            })
          })
        })
      })
    })
  },
  render6(canvas, ctx){
    const that = this
    that.drawSmallpic3(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawSmalltag3(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawCanvas6(canvas)
      })
    })
  },
  // 绘制分享小图
  drawSmallpic3(ctx,canvas){
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    const that = this
    
    let item = this.data.buyedItem,
        txt1 = '抢券价 ￥',
        priceNew = '',
        txt2 = '京东价',
        priceOld = '¥' + item.price
    if(item.coupons){
      priceNew = format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = priceOld
    }
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 500, 500);
        ctx.fillStyle = '#FF5555'
        ctx.fillRect(0,320,500,80)
        ctx.font = "bold 22px PingFangSC-Semibold";
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 16, 385);
        let txt1width = ctx.measureText(txt1).width + 16
        ctx.font = "bold 50px PingFangSC-Semibold";
        ctx.fillText(priceNew, txt1width, 385);
        let priceNewWidth = ctx.measureText(priceNew).width + txt1width + 20
        ctx.font = "bold 22px PingFangSC-Semibold";
        ctx.fillText(txt2, priceNewWidth, 385);
        let txt2width = ctx.measureText(txt2).width + priceNewWidth
        ctx.fillText(priceOld, txt2width, 385);
        let priceOldWidth = ctx.measureText(priceOld).width
        ctx.beginPath()
        ctx.strokeStyle = '#fff'
        ctx.moveTo(txt2width, 376)
        ctx.lineTo(txt2width + priceOldWidth, 376)
        ctx.stroke()
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  // 绘制商品标签
  drawSmalltag3(ctx,canvas){
    const that = this
    let item = this.data.buyedItem
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 12, 12, 200, 36);
        ctx.font = "20px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 146, 38);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 46, 38);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制内容
  drawIteminfo3(ctx,canvas){
    console.log('开始绘图')
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }

        finalStr += name[i];
        if (length > 18) {
          break;
        }
      }
      return finalStr;
    }
    var row2size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        if (length > 19) {
          finalStr += name[i];
        }
        if (length > 35) {
          break;
        }
      }
      return finalStr + '...';
    }
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    let item = this.data.buyedItem,
        itemName = item.title,
        str1 = row1size(itemName),
        str2 = row2size(itemName),
        priceNew = '',
        priceOld = format(item.price),
        priceNewTxt = '抢券价',
        priceOldTxt = '京东价'
        // txt1 = solitaire.partnerCount + '人参与了群接龙567'
    if(item.coupons){
      priceNew = format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = priceOld
    }
    const that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        ctx.font = "30px PingFangSC-Medium";
        ctx.fillStyle = "#363636";
        ctx.textAlign = 'center';
        ctx.fillText(str1, 414, 904);
        ctx.fillText(str2, 414, 946);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.fillText(priceNewTxt, 303, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceNew, 303, 1058);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#505050";
        ctx.fillText(priceOldTxt, 530, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceOld, 530, 1058);
        let lineWidth = ctx.measureText(priceOld).width
        console.log('线长度',lineWidth)
        ctx.beginPath()
        ctx.strokeStyle = '#D6D6D6'
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1008)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1044)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.strokeStyle = '#505050'
        ctx.lineWidth = 2;
        let lineX1 = 530 - lineWidth/2,
            lineX2 = 530 + lineWidth/2
        ctx.moveTo(lineX1, 1040)
        ctx.lineTo(lineX2, 1040)
        ctx.stroke()
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/zc_share@3x.jpg'
    })
  },
  drawCashbackinfo3(ctx,canvas){
    let item = this.data.buyedItem
    let txt = '下单再返' + item.estimatePoint + '元'
    let x = 64,y = 1136, r = 12, w = 700, h = 80
    const that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        ctx.save()
        ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.fillStyle = "#FDF7F1";
        ctx.fill()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.restore();
        ctx.textAlign = 'center';
        ctx.fillStyle = "#FF5555";
        ctx.font = "32px PingFangSC-Medium";
        ctx.fillText(txt, 414, 1190);
        console.log('img loaded')
        ctx.drawImage(img, 380, 1100, 72, 52);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/red.png'
      
      
    })
  },
  // 绘制商品图
  drawItemPic3(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        var x = 134,y = 264, r = 8, w = 560, h = 560
        ctx.save()
        ctx.beginPath()
        // ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        // ctx.stroke()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.drawImage(img, 134, 264, 560, 560);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.buyedItem.image
    })
  },
  // 绘制标签
  drawItemTag3(ctx,canvas){
    const that = this
    let item = this.data.buyedItem
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 292, 798, 244, 52);
        ctx.font = "26px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 454, 834);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 330, 834);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制头像
  drawAvatar3(ctx,canvas){
    const that = this
    let txt1 = app.globalData.userInfo.nickname + '分享给你一个超值商品',
        txt2 = '长按识别二维码进入京多多'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = app.globalData.userInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode3(ctx,canvas){
    const that = this
    if(app.globalData.userInfo.hasShop){
      fromOf = '&fO=fsk'
    }else{
      fromOf = '&fO=fod'
    }
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + app.globalData.userInfo.userId + '&sku=' + that.data.buyedItem.skuId + fromOf
      console.log(scene.length)
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/itemdetail/itemdetail',
          page: 'pages/itemdetail/itemdetail',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 生成图片
  drawCanvas5(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          wx.hideLoading()
        }
      })
    })
  },
  drawCanvas6(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true,
            sharetxt: '超实惠的价格，不分享一下嘛'
          })
          wx.hideLoading()
        }
      })
    })
  },
  // 已购商品分享end
  
  // 分享商铺begin
  getFreeitems() {
    console.log(1)
    const that = this
    common.post({ url: '/app/v2/shop/free99', data: { userId: app.globalData.userId, pageNo: 1,pageSize: 9 } })
      .then((res) => {
        console.log(res.data)
        that.setData({
          shopfreeitems: res.data.data,
          shopfreeloaded: true
        });
        console.log(that.data.freeitems)
      }).catch((res) => {
        console.log(res)
      })
  },
  getShopItem() {
    this.setData({
      loading: true
    })
    const that = this
    common.post({
      url: '/app/v2/shop/list', data: { sessionId: app.globalData.sessionId, userId: app.globalData.userId, pageNo:1 }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data.total)
          that.setData({
            shopitems: res.data.data,
            shopitemloaded: true
          })
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getsystemItem() {
    this.setData({
      loading: true
    })
    const that = this
    common.post({
      url: '/app/v2/shop/systemChose', data: { sessionId: app.globalData.sessionId, userId: app.globalData.userId, pageNo:1 }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data.total)
          that.setData({
            systemitems: res.data.data,
            systemitemsloaded: true
          })
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  shareShop(){
    wx.showLoading({
      title: '生成中...',
      mask: true
    })
    this.setData({
      shareStore: true
    })
    if(app.globalData.userInfo.hasShop){
      
      this.getFreeitems()
      this.getShopItem()
      this.getsystemItem()
      const that = this
      let promise = new Promise((resolve, reject) => {
        let timer = setInterval(() => {
          if (that.data.shopfreeloaded && that.data.shopitemloaded && that.data.systemitemsloaded && that.data.shopInfo !== []) {
            clearInterval(timer);
            resolve(app.globalData);
            console.log('获取数据完成')
            var freeitems = this.data.shopfreeitems,
            systemItems = this.data.systemitems
            items = this.data.shopitems,
            sub1 = [],sub2=[],sub3=[],shareItems=[],shareItems2=[]
            if(freeitems.length > 2){
              console.log('免单商品3个以上')
              sub1 = freeitems.slice(0,3);
              this.setData({
                thisfreeTxt: '0元购'
              })
              shareItems2 = sub1
              if(items.length > 2){
                console.log('小铺商品3个以上')
                sub2 = items.slice(0,3);
                shareItems = [...sub1,...sub2]
              }else{
                console.log('小铺商品不足3个')
                for(let i=0;i<items.length;i++){
                  sub2.push(items[i])
                }
                var num = 3 - items.length
                for(let i=0;i<num;i++){
                  sub3.push(systemItems[i])
                }
                shareItems = [...sub1,...sub2,...sub3]
              }
            }else{
              console.log('免单商品不足3个')
              this.setData({
                thisfreeTxt: '上新'
              })
              for(let i=0; i<freeitems.length; i++){
                sub1.push(freeitems[i]) 
              }
              var num = 6 - freeitems.length
              if(items.length > num){
                console.log('小铺商品加免单商品6个以上')
                sub2 = item.slice(0,num);
                shareItems = [...sub1,...sub2]
              }else{
                console.log('小铺商品加免单商品不足6个')
                console.log(systemItems)
                for(let i=0; i<items.length; i++){
                  sub2.push(items[i]) 
                }
                for(let i=0; i<num; i++){
                  sub3.push(systemItems[i])
                }
                shareItems = [...sub1,...sub2,...sub3]
              }
              if(items.length > 3){
                sub2 = items.slice(0,3);
                shareItems2 = sub2
              }else if(items.length > 0){
                var num = 3 - freeitems.length
                for(let i=0; i<items.length; i++){
                  sub2.push(items[i]) 
                }
                for(let i=0; i<num; i++){
                  sub3.push(systemItems[i])
                }
                shareItems2 = [...sub2,...sub3]
              }else{
                sub2 = systemItems.slice(0,3);
              }
            }
            console.log(shareItems)
            console.log(shareItems2)
            this.setData({
              shareItem: shareItems,
              shareItem2: shareItems2
            })
            console.log('选择画布')
            const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
            query.select('#canvas').fields({
              node: true,
              rect: true
            }, res => {
              const canvas = res.node;
              const ctx = canvas.getContext('2d');
              canvas.width = 828;//本地图像的width
              canvas.height = 1472;//本地图像的height
              this.render7(canvas, ctx);
            }).exec()
          } else {
            //todo 信息构建中
          }
        }, 250);
      });
    }else{
      this.canvas9()
    }
    
  },
  canvas7(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render8(canvas, ctx);
    }).exec()
  },
   // 生成分享图

   render7(canvas, ctx) {
    const that = this
    this.drawIteminfo4(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawShopInfo4(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawshopkeeper4(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawDcode4(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawItem4(ctx,canvas,0).then(function(){
              console.log('第五步完成')
              that.drawItem4(ctx,canvas,1).then(function(){
                console.log('第六步完成')
                that.drawItem4(ctx,canvas,2).then(function(){
                  console.log('第七步完成')
                  that.drawItem4(ctx,canvas,3).then(function(){
                    console.log('第八步完成')
                    that.drawItem4(ctx,canvas,4).then(function(){
                      console.log('第九步完成')
                      that.drawItem4(ctx,canvas,5).then(function(){
                        console.log('第十步完成')
                        that.drawTag4(ctx,canvas).then(function(){
                          console.log('第十一步完成')
                          that.drawCanvas7(canvas)
                        })
                        
                      })
                    })
                  })
                })
              })
            })
          })
        })
      })
      // that.canvas1()
    })
  },
  render8(canvas, ctx){
    const that = this
    that.drawSmallpic4(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemSmall4(ctx,canvas,0).then(function(){
        console.log('第二步完成')
        that.drawItemSmall4(ctx,canvas,1).then(function(){
          console.log('第三步完成')
          that.drawItemSmall4(ctx,canvas,2).then(function(){
            console.log('第四步完成')
            that.drawCanvas8(canvas)
          })
        })
      })
    })
  },
  drawIteminfo4(ctx,canvas){
    console.log('开始绘图')
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/shop_share@3x.jpg'
    })
  },
  drawShopInfo4(ctx,canvas){
    const that = this
    let txt1 = this.data.shopInfo.shopName
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 72, x = 342, y = 60
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 142, 142);
        ctx.restore()
        console.log('绘制头像完成')
        ctx.strokeStyle = "#ffffff";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "44px PingFangSC-Semibold";
        }else{
          ctx.font = "bold 44px NotoSans-Bold";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(txt1, 414, 238);
        console.log('绘制文字完成')
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  drawTag4(ctx,canvas){
    let txt2 = this.data.shopInfo.fansCount + '位粉丝'
    let x = 352,y = 276, r = 4, w = 126, h = 40
    return new Promise(function (resolve, reject) {
      ctx.beginPath()
      ctx.save()
      // ctx.beginPath()
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      // 这里是使用 fill 还是 stroke都可以，二选一即可
      // ctx.fillStyle = 'transparent'
      ctx.fillStyle = 'transparent'
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
      // 右上角
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
      // 左下角
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
      ctx.fillStyle = 'rgba(255, 255, 255, 0.2)'
      ctx.fill()
      ctx.closePath()
      // 剪切
      ctx.clip()
      ctx.restore();
      if(app.globalData.isIphone){
        ctx.font = "22px PingFangSC-Semibold";
      }else{
        ctx.font = "bold 22px NotoSans-Bold";
      }
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillStyle = "#fff";
      ctx.fillText(txt2, 414, 296);
      ctx.closePath();
      resolve()
    })
  },
  // 绘制头像
  drawshopkeeper4(ctx,canvas){
    const that = this
    let txt1 = this.data.shopInfo.ownerName + ' 邀请你进入他的小店',
        txt2 = '长按识别二维码进入小店'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode4(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + that.data.fromUserId
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/shareShop/shareShop',
          page: 'pages/itemlist/itemlist',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            ctx.closePath();
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }else{
          wx.hideLoading()
          that.loginTip()
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 绘制商品图1
  drawItem4(ctx,canvas,i){
    const that = this
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        finalStr += name[i];
        if (length > 8) {
          break;
        }
      }
      return finalStr;
    }
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    switch(i){
      case 0:
        var x = 48,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 120, circleY = 784, circleR = 20,
            circleX2 = 204, 
            rectangleX = 120, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 162, txt1Y = 740,
            txt2X = 162, txt2Y = 786,
            priceNewX = 159, priceNewY = 795,
            priceOldX = 165, priceOldY = 797
        break;
      case 1:
        var x = 300,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 372, circleY = 784, circleR = 20,
            circleX2 = 456, 
            rectangleX = 372, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 414, txt1Y = 740,
            txt2X = 414, txt2Y = 786,
            priceNewX = 413, priceNewY = 795,
            priceOldX = 417, priceOldY = 797
        break;
      case 2:
        var x = 552,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 584, circleY = 784, circleR = 20,
            circleX2 = 668, 
            rectangleX = 584, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 667, txt1Y = 740,
            txt2X = 667, txt2Y = 786,
            priceNewX = 664, priceNewY = 795,
            priceOldX = 670, priceOldY = 797
        break;
      case 3:
        var x = 48,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 120, circleY = 1174, circleR = 20,
            circleX2 = 204, 
            rectangleX = 120, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 162, txt1Y = 1134,
            txt2X = 162, txt2Y = 1176,
            priceNewX = 159, priceNewY = 1185,
            priceOldX = 165, priceOldY = 1187
        break;
      case 4:
        var x = 300,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 372, circleY = 1174, circleR = 20,
            circleX2 = 456, 
            rectangleX = 372, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 414, txt1Y = 1134,
            txt2X = 414, txt2Y = 1176,
            priceNewX = 413, priceNewY = 1185,
            priceOldX = 417, priceOldY = 1187
        break;
      case 5:
        var x = 552,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 584, circleY = 1174, circleR = 20,
            circleX2 = 668, 
            rectangleX = 584, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 667, txt1Y = 1134,
            txt2X = 667, txt2Y = 1176,
            priceNewX = 664, priceNewY = 1185,
            priceOldX = 670, priceOldY = 1187
        break;
    }
    console.log(i)
    console.log(that.data.shareItem[i])
    var item = that.data.shareItem[i]
    var txt1 = row1size(item.title),
        txt2 = '限时免单'
    var priceNew = '',
        priceOld = '￥' + item.price
    var lineWidth = ctx.measureText(priceOld)
    if(item.coupons){
      priceNew = '￥' + format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = '￥' + priceOld
    }
    
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        ctx.beginPath()
        console.log('img loaded')
        ctx.save()
        ctx.setFillStyle = 'transparent'
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.closePath()
        ctx.clip()
        ctx.drawImage(img, x, y, w, h);
        ctx.restore();
        ctx.beginPath()
        if(app.globalData.isIphone){
          ctx.font = "23px PingFangSC-Medium";
        }else{
          ctx.font = "23px NotoSans-Medium";
        }
        ctx.fillStyle = "#505050";
        ctx.textAlign = 'center';
        ctx.fillText(txt1, txt1X, txt1Y);
        console.log(item.is99)
        if(item.is99){
          ctx.arc(circleX1,circleY,circleR,0,2*Math.PI)
          ctx.fillStyle = "#FFE232"
          ctx.fill()
          ctx.arc(circleX2,circleY,circleR,0,2*Math.PI)
          ctx.fillStyle = "#FFE232"
          ctx.fill()
          ctx.fillRect(rectangleX,rectangleY,rectangleW,rectangleH)
          ctx.fillStyle = "#000";
          ctx.fillText(txt2, txt2X, txt2Y);
        }else{
          if(app.globalData.isIphone){
            ctx.font = "27px PingFangSC-Semibold";
          }else{
            ctx.font = "bold 27px NotoSans-Bold";
          }
          ctx.fillStyle = "#FF5555";
          ctx.textAlign = 'right';
          ctx.fillText(priceNew, priceNewX, priceNewY);
          if(app.globalData.isIphone){
            ctx.font = "23px PingFangSC-Semibold";
          }else{
            ctx.font = "bold 23px NotoSans-Bold";
          }
          ctx.fillStyle = "#BCBCBC";
          ctx.textAlign = 'left';
          ctx.fillText(priceOld, priceOldX, priceOldY);
          ctx.fillStyle = "#BCBCBC";
          ctx.fillRect(priceOldX, priceOldY - 4, lineWidth.width, 2)
        }
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  // 生成图片
  drawCanvas7(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          that.canvas7()
        }
      })
    })
  },
  // 绘制分享小图
  drawSmallpic4(ctx,canvas){
    const that = this
    let shopName = this.data.shopInfo.shopName,
        txt1 = '以上为今日' + this.data.thisfreeTxt + '的商品哦',
        txt2 = '快来看看吧！'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        ctx.fillStyle = '#FF5555'
        ctx.fillRect(0,0,500,400)
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(shopName, 128, 68);
        ctx.textAlign = 'center';
        ctx.font = "bold 32px PingFangSC-Semibold";
        ctx.fillStyle = '#FFF617'
        ctx.fillText(txt1, 250, 334);
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillText(txt2, 250, 368);
        let r = 46, x = 9, y = 9
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  drawItemSmall4(ctx,canvas,i){
    const that = this
    switch(i){
      case 0:
        var x = 16,y = 136, r = 4, w = 152, h = 152
        break;
      case 1:
        var x = 174,y = 136, r = 4, w = 152, h = 152
        break;
      case 2:
        var x = 332,y = 136, r = 4, w = 152, h = 152
        break;
    }
    console.log(i)
    console.log(that.data.shareItem[i])
    var item = that.data.shareItem[i]
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        ctx.beginPath()
        console.log('img loaded')
        ctx.save()
        ctx.setFillStyle = 'transparent'
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.closePath()
        ctx.clip()
        ctx.drawImage(img, x, y, w, h);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  drawCanvas8(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true,
            sharetxt: '小铺开张大吉，财源广进'
          })
          wx.hideLoading()
        }
      })
    })
  },
  // 分享商铺end
  // 分享海报begin
  canvas9(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 828;//本地图像的width
      canvas.height = 1472;//本地图像的height
      this.render9(canvas, ctx);
    }).exec()
  },
  render9(canvas, ctx){
    const that = this
    that.drawBigpic5(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawshopkeeper5(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawDcode5(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawCanvas9(canvas)
        })
      })
    })
  },
  // 绘制大图背景
  drawBigpic5(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/jddsharebg@3x.jpg'
    })
  },
  // 绘制头像
  drawshopkeeper5(ctx,canvas){
    const that = this
    let txt1 = app.globalData.userInfo.nickname + ' 邀请你进入京多多',
        txt2 = '长按识别二维码进入京多多'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = app.globalData.userInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode5(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + that.data.fromUserId
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/shareShop/shareShop',
          page: 'pages/itemlist/itemlist',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            ctx.closePath();
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }else{
          wx.hideLoading()
          that.loginTip()
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  drawCanvas9(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          that.canvas10()
        }
      })
    })
  },
  canvas10(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render10(canvas, ctx);
    }).exec()
  },
  render10(canvas, ctx){
    const that = this
    that.drawSmallpic5(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawCanvas10(canvas)
      
    })
  },
  drawSmallpic5(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 500, 400);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/jddsharebg_s@3x.jpg'
    })
  },
  drawCanvas10(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true,
            sharetxt: '分享我的海报，获取更多粉丝'
          })

          wx.hideLoading()
        }
      })
    })
  },
  //分享海报end
  saveSharePic(){
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imgSrc,
      success: function (data) {
          wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
          })
      },
      fail: function (err) {
          console.log(err);
          if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权")
              wx.openSetting({
                  success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                  }
              })
          } else {
              wx.showToast({
                  title: '保存失败',
                  icon: 'none'
              });
          }
      },
      complete(res) {
          console.log(res);
      }
    })
  },
  closeSharePic(){
    console.log('关闭')
    this.setData({
      showshareBox: false
    })
  },
})
